package com.anxin.registerManagement.config.shiro;

import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.pam.AuthenticationStrategy;
import org.apache.shiro.authc.pam.ModularRealmAuthenticator;
import org.apache.shiro.realm.Realm;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.Collection;
/**
 * @author 叶前呈
 * @date 2022/1/24 16:22
 * @descrpition 主要是为了解决多个realm下的异常问题
 */
public class MultiRealmAuthenticator extends ModularRealmAuthenticator {

    private static  Logger logger = LoggerFactory.getLogger(ModularRealmAuthenticator.class);

    /**
     * 重写多realm校验方法，避免无法捕获到realm中的自定义异常
     * 取消执行代码 realm.getAuthenticationInfo(token); 的tey catch
     * 多个realm时候，如果其中一个realm抛出异常则直接抛出异常，类似single方法，
     * @param realms
     * @param token
     * @return
     */
    @Override
    protected AuthenticationInfo doMultiRealmAuthentication(Collection<Realm> realms, AuthenticationToken token) {
        AuthenticationStrategy strategy = getAuthenticationStrategy();
        AuthenticationInfo aggregate = strategy.beforeAllAttempts(realms, token);
        if (logger.isTraceEnabled()) {
            logger.trace("Iterating through {} realms for PAM authentication", realms.size());
        }
        for (Realm realm : realms) {
            aggregate = strategy.beforeAttempt(realm, token, aggregate);
            if (realm.supports(token)) {
                logger.trace("Attempting to authenticate token [{}] using realm [{}]", token, realm);
                AuthenticationInfo info = null;
                Throwable t = null;
                info = realm.getAuthenticationInfo(token);
                //当匹配到info就返回不再继续查询
                if (info !=null){
                    return aggregate = strategy.afterAttempt(realm, token, info, aggregate, t);
                }
            } else {
                logger.debug("Realm [{}] does not support token {}.  Skipping realm.", realm, token);
            }
        }
        aggregate = strategy.afterAllAttempts(token, aggregate);
        return aggregate;
    }
}
